package com.sinog.front.service.user;

import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.front.feign.basic.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @desc 使用门面模式获取用户的登陆信息
 * @author zy
 * @date 2019年8月15日 09点26分
 */
@Component
public class UserFacade implements IAuthenticationFacade {

    @Autowired
    private UserService userService;

    /**
     * 获取用户
     * @return UserDTO
     */
    @Override
    public UserDTO getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!(authentication instanceof AnonymousAuthenticationToken)) {
            String account = authentication.getName();
            Result result = userService.selectOne(account,Constants.NumberStr.NUM_STR_ZERO);
            if(Constants.Number.NUM_ONE.equals(result.getCode())) {
                String data = (String)result.getData();
                return JsonUtil.toBean(data, UserDTO.class);
            }
        }
        UserDTO userDTO = new UserDTO();
        userDTO.setAccount("annonUser");
        userDTO.setUsername("匿名用户");
        userDTO.setPositionName("无职位");
        return userDTO;
    }
}